﻿@page "/WorkFlowFile"
@using Tewr.Blazor.FileReader
@using WorkFlow.Data
@using WorkFlow.Data.Model
@inject IFileReaderService fileReaderService
@inject List<WorkFlowFileEntity> workFlowFileEntityList
@inject IJSRuntime JSRunTime
@inject DataManager dataManager
<h3>WorkFlowFile</h3>
<div>
    WorkFlowName&nbsp;<input type="text" id="Search_WorkflowName" @bind="@_workFlowName">
    &nbsp;&nbsp;<button type="button" class="btn btn-primary" @onclick="Search">Search</button>
    <div style="float:right;">
        &nbsp;&nbsp;<input @ref=inputTypeFileElement accept=".vdx" type="file" /><button @onclick=UpLoadFile>上传文件</button>
        <div>
            @if (!string.IsNullOrEmpty(_src))
            {
                @*<img src="@_src" width="600px" />*@
            }
            else
            {
                <p>@progress</p>
            }
        </div>
    </div>
</div>
<div>
    <table class="table">
        <thead>
            <tr>
                <th>Sno</th>
                <th>ID</th>
                <th>Name</th>
                <th>FileName</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            @if (workFlowFileEntityList != null)
            {
                for (var i = 0; i < workFlowFileEntityList.Count; i++)
                {
                    WorkFlowFileEntity workFlowFileEntity = workFlowFileEntityList[i];
                    <tr>
                        <td>@(i+1)</td>
                        <td>@workFlowFileEntity.ID</td>
                        <td>@workFlowFileEntity.Name</td>
                        <td>@workFlowFileEntity.FileName</td>
                        <td><button class="btn btn-outline-primary" @onclick="@(()=>EditRule(@workFlowFileEntity.ID,@workFlowFileEntity.Name))" data-toggle="modal" data-target="#EditWorkFlowFile">Edit</button></td>
                        <td><button class="btn btn-primary" @onclick="@(()=>DeleteRule(@workFlowFileEntity.ID))">Delete</button></td>
                    </tr>
                }
            }
        </tbody>
    </table>
</div>


<div class="modal fade" id="EditWorkFlowFile" tabindex="-1" role="dialog" aria-labelledby="ParamertersLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="title">Rule</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="model-body">
                &ensp;WorkFlowFileName&nbsp;
                <input type="text" id="Name" @bind="@_EditName" style="width: 100%;">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">close</button>
                <button type="button" class="btn btn-primary" @onclick="Save">Save</button>
            </div>
        </div>

    </div>
</div>

@code {
    private IJSObjectReference module;
    private ElementReference inputTypeFileElement;
    private string _src;
    private string _workFlowName;
    private string progress;
    private int _EditID;
    private string _EditName;
    protected override async void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            module = await JSRunTime.InvokeAsync<IJSObjectReference>("import", "/vendor/MyJS.js");
            Search();
        }
    }
    async void UpLoadFile()
    {
        _src = "";
        foreach (var file in await fileReaderService.CreateReference(inputTypeFileElement).EnumerateFilesAsync())
        {
            await using var fileStream = await file.OpenReadAsync();
            var buffer = new byte[2048];
            var finalBuffer = new byte[fileStream.Length];
            int count;
            int totalCount = 0;
            while ((count = await fileStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
            {
                Buffer.BlockCopy(buffer, 0, finalBuffer, totalCount, count);
                totalCount += count;
                progress = "UpLoadFile: " + (int)(totalCount * 100.0 / fileStream.Length) + "%";
                StateHasChanged();
            }
            //_src = $"data:image/jpg;base64,{Convert.ToBase64String(finalBuffer)}";
            progress = "UpLoad Complete";
            StateHasChanged();
            string fileName = file.ReadFileInfoAsync().Result.Name;
            string savePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\WorkFlow", fileName);
            if (File.Exists(savePath))
            {
                bool bo = await this.module.InvokeAsync<bool>("IsContinue", $"a file named 【{fileName}】 already exists on the server. Do you want to overwrite it?");
                if (!bo)
                {
                    return;
                }
            }

            File.WriteAllBytes(savePath, finalBuffer);
            WorkFlowFileEntity workFlowFileEntity = new WorkFlowFileEntity();
            workFlowFileEntity.GroupID = 0;
            workFlowFileEntity.Name = fileName.Split('.')[0];
            workFlowFileEntity.FileName = fileName;
            int id = dataManager.InsertWorkFlowFileEntity(workFlowFileEntity);
            workFlowFileEntity.ID = id;
            workFlowFileEntityList.Add(workFlowFileEntity);
            StateHasChanged();
        }

    }
    private void Search()
    {
        workFlowFileEntityList = dataManager.GetWorkFlowFileEntity(_EditName);
        UpdateUI();
    }
    private void EditRule(int ID, string editName)
    {
        _EditID = ID;
        _EditName = editName;
    }

    private async void DeleteRule(int ID)
    {
        bool bo = await this.module.InvokeAsync<bool>("IsContinue", "Are you sure delete this WorkFlowFile?");
        if (bo)
        {
            dataManager.DeleteWorkFlowFileEntity(ID);
            WorkFlowFileEntity workFlowFileEntity = workFlowFileEntityList.Find(a => a.ID == ID);
            workFlowFileEntityList.Remove(workFlowFileEntity);
            UpdateUI();
        }
    }

    private void Save()
    {
        string result = dataManager.UpdateWorkFlowFileEntityName(_EditID, _EditName);
        if (string.IsNullOrEmpty(result))
        {
            this.module.InvokeVoidAsync("CloseDialog", "close");
            Search();
        }
        else
        {
            this.module.InvokeAsync<bool>("IsContinue", result);
        }
    }

    private async void UpdateUI()
    {
        await InvokeAsync(() => StateHasChanged());
    }

}
